package 多线程.安全.同步方法;

import sun.plugin2.os.windows.Windows;

/**
 * @Projectname java_based
 * @Filename WindowTest4
 * @Author an
 * @Data 2022/7/12 8:28
 * @Description TODO
 */
class Windows4 implements Runnable{

    private int ticket = 100;
    @Override
    public  void run() {

        while (show()) {
//            if (!show()){
//                break;
//            }

//            synchronized (this) {
//                if (ticket > 0) {
//
//
//                    try {
//                        Thread.sleep(100);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//
//
//                    System.out.println(Thread.currentThread().getName() + ":" + ticket);
//                    ticket--;
//                } else {
//                    break;
//                }
//            }
        }
    }

    private synchronized boolean show(){//同步监视器：this  默认
//        synchronized (this){}
        if(ticket > 0){


            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            System.out.println(Thread.currentThread().getName() + ":" + ticket);
            ticket--;

            return true;
        }else {
            return false;
        }


    }
}


public class WindowTest4 {
    public static void main(String[] args) {

        Windows4 w = new Windows4();
        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();

    }

}